<script setup lang="ts">
import { computed, ref } from 'vue';
import { notification } from 'ant-design-vue';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import { modalSchema } from './user';
import { getUser, createUser, updateUser, getRoleAlls, getUserRoles } from '#/api/abp/user'; // 确保导入 getRoles
import type { RoleDto } from '#/api/abp/user/types'; // 确保导入 RoleDto
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const roleOptions = ref<{ label: string; value: string }[]>([]); // 定义角色选项

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 80,
  },
  showDefaultActions: false,
  wrapperClass: 'grid grid-cols-2 gap-4',
  // 将角色选项传递给表单
  schema: modalSchema().map(schema => {
    if (schema.fieldName === 'roleNames') {
      return {
        ...schema,
        componentProps: {
          ...schema.componentProps,
          options: roleOptions, // 将动态获取的选项赋值给 RadioGroup
        },
      };
    }
    return schema;
  }),

});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    // 获取角色列表
    const res = await getRoleAlls();
    roleOptions.value = res?.items?.map((role: RoleDto) => ({
      label: role.name,
      value: role.name,
    }));

    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const user = await getUser(id);
      const userRole = await getUserRoles(id);
      user.roleNames = userRole?.items?.map((role: RoleDto) => role.name);
      // 填充表单数据，特别是角色
      await formApi.setValues({
        ...user,
      });
    } else {
      // 新增模式，重置表单并清空数据
      await formApi.resetForm();
      // 设置默认选中的角色
      const defaultRole = res?.items?.find(role => role.isDefault);
      if (defaultRole) {
        await formApi.setFieldValue('roleNames', defaultRole.name);
      }
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues());

    // 确保 roleNames 是一个数组
    const apiData = {
      ...data,
      roleNames: Array.isArray(data.roleNames) ? data.roleNames : (data.roleNames ? [data.roleNames] : []),
    };

    console.log('API Request Data:', apiData); // 添加日志

    await (isUpdate.value ? updateUser(data.id, apiData) : createUser(apiData));
    resetInitialized();
    emit('reload');
    modalApi.close();
    notification['success']({
    duration: 2,
    message: isUpdate.value? $t('pages.common.editSuccess') : $t('pages.common.addSuccess'),
  });
  }
  catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title" class="w-[800px] h-[480px]">
    <BasicForm />
  </BasicModal>
</template>
